<!--
 * @Author: Lizhenyu
 * @Date: 2021-09-02 16:12:36
 * @FilePath: \usp-osm-frondend\src\views\shopConfig\pageMgmt.vue
-->
<template>
  <div class="source" v-loading="pageLoading" element-loading-text="加载中...">
    <div class="page-head">
      <el-button :disabled="checkAuth()" class="search-btn dark-btn" @click="toPreview('preview')">
        预览
      </el-button>
      <el-button :disabled="checkAuth()" class="search-btn dark-btn" @click="toPreview('save')">发布</el-button>
    </div>

    <!-- banner setting -->
    <div class="banner-setting">
      <h1>轮播图配置</h1>
      <v-notes>
        <el-form
          label-width="80px"
          :model="bannerForm"
          ref="searchForm"
          class="setting-form"
          size="small"
        >
          <el-row class="search-row">
            <el-col :span="24">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="展示页面">
                    <el-select
                      @change="dataChange"
                      v-model="bannerForm.showPage"
                      placeholder="请选择"
                    >
                      <el-option label="商城首页" value="1000"></el-option>
                      <el-option
                        v-for="item in bannerList"
                        :key="item.id"
                        :label="item.categoryName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" style="text-align: right">
                  <el-button
                    :disabled="checkAuth()"
                    @click="saveBannerList"
                    class="dark-btn search-btn"
                  >保存</el-button>
                  <el-button
                    @click="closeFilter"
                    :icon="
                      showContent ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                    "
                    class="white-btn filterClose"
                  >
                    {{ showContent ? '折叠' : '展开' }}
                  </el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </v-notes>
      <el-collapse-transition>
        <div class="filterContent" v-if="showContent">
          <div class="mb-lg">
            <v-table
              :data="bannerTableData"
              ref="multipleTable"
              :listLoading="listLoading"
              loadingText="...加载中"
              border
              :pagination="false"
            >
              <div slot="header">
                <el-button
                  @click="addBanner"
                  :disabled="bannerTableData.length>=9 || checkAuth()"
                  icon="el-icon-plus"
                  class="dark-btn"
                  style="margin-bottom: 0 !important"
                  >新增</el-button
                >
              </div>
              <el-table-column label="序号" align="center">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                label="图片"
                align="center"
                min-width="110"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="myHeaders"
                    :on-progress="uploadProgress"
                    :show-file-list="false"
                    :disabled="!scope.row.isChange"
                    :on-error="uploadError"
                    :on-success="res => imageUpload(res, scope.row)"
                    :before-upload="beforeUpload">
                    <img v-if="scope.row.imagePath" :src="scope.row.imagePath" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column
                label="跳转链接"
                align="center"
                min-width="110"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <span v-if="scope.row.isChange">
                    <el-input v-model="scope.row.redirectUrl" size="mini"></el-input>
                  </span>
                  <span v-else>
                    {{ scope.row.redirectUrl }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                label="展示顺序"
                align="center"
                min-width="60"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <span v-if="!scope.row.isChange">{{ scope.row.sort }}</span>
                  <div v-else>
                    <el-input-number
                      v-model="scope.row.sort"
                      :controls="false"
                      :step-strictly="true"
                      :min="1"
                      size="mini"
                    >
                    </el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="140"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <el-row type="flex" justify="space-around">
                    <el-col v-if="!scope.row.isChange">
                      <el-button :disabled="checkAuth()" @click="editBanner(scope.row, scope.$index)">
                        编辑
                      </el-button>
                    </el-col>
                    <el-col v-if="!scope.row.isChange">
                      <el-button
                        :disabled="checkAuth()"
                        @click="deleteBanner(bannerTableData, scope.$index)"
                      >
                        删除
                      </el-button>
                    </el-col>
                    <el-col v-if="scope.row.isChange">
                      <el-button
                        :disabled="checkAuth()"
                        class="dark-btn search-btn"
                        @click="saveBanner(scope.row, scope.$index)"
                      >
                        确定
                      </el-button>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </v-table>
          </div>
        </div>
      </el-collapse-transition>
    </div>
    <!-- list page setting -->
    <div class="list-setting">
      <div class="setting-header">
        <h1>列表页配置</h1>
        <el-button class="search-btn" style="margin-top: 10px" :disabled="checkAuth()" @click="addMoudle">新增专区</el-button>
      </div>
      <div class="page-section" v-for="(item, index) in formList" :key="index">
        <v-notes>
          <el-form
            label-width="80px"
            :model="item"
            ref="listForm"
            class="setting-form"
            size="small"
          >
            <el-row class="search-row">
              <el-col :span="24">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="选择专区">
                      <el-select
                        @change="val => selectChange(val, item)"
                        v-model="item.categoryId"
                        :disabled="!item.isAdd"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="items in pageList"
                          :key="items.id"
                          :label="items.categoryName"
                          :disabled="items.disabled"
                          :value="items.id"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" style="text-align: right">
                    <el-button v-if="!item.isAdd" @click="refreshList(item)" class="dark-btn search-btn">刷新</el-button>
                    <el-button
                      :disabled="checkAuth()"
                      @click="saveCategory(item)"
                      class="dark-btn search-btn"
                    >保存</el-button>
                    <el-button
                      :disabled="checkAuth()"
                      @click="delCategory(item, index)"
                      class="dark-btn search-btn"
                    >删除</el-button>
                    <el-button
                      @click="listCloseFilter(item)"
                      :icon="
                        item.listShowContent
                          ? 'el-icon-arrow-up'
                          : 'el-icon-arrow-down'
                      "
                      class="white-btn filterClose"
                    >
                      {{ item.listShowContent ? '折叠' : '展开' }}
                    </el-button>
                    <el-button :disabled="checkAuth()" @click="updateSort(item.categoryId,'SHIFT_DOWN')" class="white-btn" v-if="item.sort < length">下移</el-button>
                    <el-button :disabled="checkAuth()" @click="updateSort(item.categoryId,'SHIFT_UP')" class="white-btn" v-if="item.sort > 1">上移</el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </v-notes>
        <el-collapse-transition>
          <div class="filterContent" v-if="item.listShowContent && item.categoryId">
            <div class="mb-lg">
              <v-table
                :data="item.productDisplayList"
                ref="multipleTable"
                :listLoading="listLoading"
                loadingText="...加载中"
                border
                :pagination="false"
              >
                <div slot="header">
                  <el-button
                    @click="addListData(item.productDisplayList)"
                    icon="el-icon-plus"
                    class="dark-btn"
                    style="margin-bottom: 0 !important"
                    >新增商品</el-button
                  >
                </div>
                <el-table-column label="序号" align="center" min-width="50">
                  <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="展示方式"
                  align="center"
                  min-width="60"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.isChange">
                      <el-select
                        v-model="scope.row.moduleStyle"
                        placeholder="请选择"
                        size="mini"
                      >
                        <el-option
                          v-for="item in lookupItems.MODULESTYLE"
                          :key="item.dicCode"
                          :label="item.dicName"
                          :value="item.dicCode"
                        >
                        </el-option>
                      </el-select>
                    </span>
                    <span v-else>
                      {{ getDictionaryNameByCode('MODULESTYLE', scope.row.moduleStyle) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  fixed="right"
                  align="center"
                  width="140"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="scope">
                    <el-row type="flex" justify="space-around">
                      <el-col v-if="!scope.row.isChange">
                        <el-button :disabled="checkAuth()" @click="editList(item.productDisplayList, scope.$index)">
                          编辑
                        </el-button>
                      </el-col>
                      <el-col v-if="!scope.row.isChange">
                        <el-button
                          :disabled="checkAuth()"
                          @click="deleteListData(item.productDisplayList, scope.$index)"
                        >
                          删除
                        </el-button>
                      </el-col>
                      <el-col v-if="scope.row.isChange">
                        <el-button
                          :disabled="checkAuth()"
                          class="dark-btn search-btn"
                          @click="saveList(scope.row)"
                        >
                          确定
                        </el-button>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
              </v-table>
            </div>
            <div class="setting-more">
              <h2>【更多】按钮配置 <span style="font-size: 12px;color: #666;">请注意：若选择‘否’，则APP端用户无法进入专区商品列表页面。</span></h2>
              <div style="margin: 20px 0 10px">
                <el-radio v-model="item.showMore" label="1">是</el-radio>
                <el-radio v-model="item.showMore" label="0">否</el-radio>
              </div>
              <div class="setting-table">
                <v-table
                  v-if="item.showMore === '1'"
                  :data="item.thirdCategoryList"
                  ref="thirdCategoryList"
                  border
                  :pagination="false"
                >
                  <el-table-column label="序号" align="center" min-width="50">
                    <template slot-scope="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="前三级类目名称"
                    align="center"
                    min-width="80"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.categoryName }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="展示顺序"
                    align="center"
                    min-width="110"
                  >
                    <template slot-scope="scope">
                      <span v-if="!scope.row.isChange">
                        {{ scope.row.sort }}
                      </span>
                      <div v-else>
                        <el-input-number
                          v-model="scope.row.sort"
                          :controls="false"
                          :step-strictly="true"
                          :min="1"
                          size="mini"
                        >
                        </el-input-number>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="140">
                    <template slot-scope="scope">
                      <el-button
                        :disabled="checkAuth()"
                        v-if="!scope.row.isChange"
                        @click="moreEdit(scope.row, scope.$index)"
                        >编辑</el-button
                      >
                      <el-button
                        v-else
                        :disabled="checkAuth()"
                        @click="moreSave(scope.row, scope.$index)"
                        class="search-btn dark-btn"
                        >确定</el-button
                      >
                    </template>
                  </el-table-column>
                </v-table>
              </div>
            </div>
          </div>
        </el-collapse-transition>
      </div>
    </div>
    <dialog-preview ref="dialogPreview"></dialog-preview>
  </div>
</template>

<script>
import Vue from 'vue'
import { cloneDeep, find } from 'lodash'
import { ACCESS_TOKEN } from '@/config/variableInit'
import VNotes from '@/components/Notes/index'
import VTable from '@/components/PageTable/index'
import { mapGetters } from 'vuex'
import { common } from '@/mixins/common'
import DialogPreview from './preview.vue'
import {
  getPagesList,
  getBannerList,
  getSaveBanner,
  getCategoryList,
  getDelPages,
  getSavePage,
  getUpdateSort,
  getRefreshData
} from '@/api/shopConfig'
export default {
  name: 'listPagesMgmt',
  components: {
    VNotes,
    VTable,
    DialogPreview
  },
  data () {
    return {
      pageLoading: false,
      uploadUrl: process.env.VUE_APP_BASE_URL + '/admin/upload/kv-image',
      myHeaders: { Authorization: Vue.ls.get(ACCESS_TOKEN) },
      formList: [],
      listLoading: false,
      showContent: true,
      // banner data source
      bannerForm: {
        showPage: '1000'
      },
      bannerList: [],
      pageList: [],
      bannerTableData: [],
      length: 0,
      isChange: false,
      isShowTable: true,
      isDisabled: false
    }
  },
  mixins: [common],
  computed: {
    ...mapGetters(['lookupItems'])
  },
  watch: {
    formList: {
      handler () {
        this.pageList.forEach(items => {
          if (find(this.formList, ['categoryId', items.id])) {
            items.disabled = true
          } else {
            items.disabled = false
          }
        })
      },
      deep: true
    }
  },
  created () {
    this.getPageList()
    this.getBannerData(this.bannerForm.showPage)
    this.getCategoryPage()
  },
  mounted () {
  },
  methods: {
    checkAuth () {
      if (this.$auth('onlineShopConfigurationManagement:pageConfiguration:detail') && this.$auth('onlineShopConfigurationManagement:pageConfiguration:edit')) {
        return false
      } else {
        return true
      }
    },
    toPreview (type) {
      this.$refs.dialogPreview.open(type)
    },
    getCategoryPage () {
      if (!this.$auth('onlineShopConfigurationManagement:pageConfiguration:detail')) {
        this.$alert('您没有权限')
        return false
      }
      this.pageLoading = true
      getCategoryList().then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            if (res.obj && res.obj.length > 0) {
              res.obj.forEach(item => {
                item.listShowContent = true
              })
              this.formList = res.obj
              this.length = res.obj.length
            } else {
              this.formList = []
            }
          }
          this.pageLoading = false
        }
      })
    },
    saveBannerList () {
      let flag = false
      this.bannerTableData.forEach(item => {
        if (item.isChange) {
          flag = true
        }
      })
      if (flag) {
        this.$alert('请先确定修改项')
        return false
      }
      this.pageLoading = true
      const datas = {
        categoryId: this.bannerForm.showPage,
        kvImageList: this.bannerTableData
      }
      getSaveBanner(datas).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            this.$alert('保存成功')
          }
          this.pageLoading = false
        }
      })
    },
    getPageList () {
      if (!this.$auth('onlineShopConfigurationManagement:pageConfiguration:detail')) {
        this.$alert('您没有权限')
        return false
      }
      this.pageLoading = true
      getPagesList({ parentId: 1000, filterWithoutChildren: true }).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            this.bannerList = cloneDeep(res.obj)
            this.pageList = res.obj
          }
          this.pageLoading = false
        }
      })
    },
    getBannerData (id) {
      if (!this.$auth('onlineShopConfigurationManagement:pageConfiguration:detail')) {
        this.$alert('您没有权限')
        return false
      }
      this.pageLoading = true
      getBannerList({ categoryId: id }).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            if (res.obj) {
              this.bannerTableData = res.obj
            } else {
              this.bannerTableData = []
            }
          }
          this.pageLoading = false
        }
      })
    },
    addMoudle () {
      const obj = {
        parentId: 1000,
        categoryLevel: 2,
        categoryId: '',
        categoryName: '',
        productDisplayList: [],
        thirdCategoryList: [],
        showMore: '1',
        listShowContent: true,
        isAdd: true
      }
      this.formList.push(obj)
    },
    getNameByCode (list, code) {
      const flagObj = list.find((item) => {
        return item.id === code
      })
      if (flagObj) return flagObj.categoryName
    },
    selectChange (id, data) {
      data.categoryName = this.getNameByCode(this.pageList, id)
      this.pageLoading = true
      getPagesList({ parentId: id }).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            if (res.obj) {
              const arr = []
              res.obj.forEach((item, index) => {
                const list = {
                  categoryId: item.id,
                  categoryName: item.categoryName,
                  sort: index + 1,
                  parentId: item.parentId,
                  categoryLevel: item.categoryLevel
                }
                arr.push(list)
              })
              data.thirdCategoryList = arr
            }
          }
          this.pageLoading = false
        }
      })
    },
    addListData (item) {
      const obj = {
        moduleStyle: '',
        isChange: true
      }
      item.push(obj)
    },
    editList (item, index) {
      const row = item[index]
      this.$set(row, 'isChange', true)
    },
    closeFilter () {
      this.showContent = !this.showContent
    },
    listCloseFilter (item) {
      if (item.listShowContent) {
        this.$set(item, 'listShowContent', false)
      } else {
        this.$set(item, 'listShowContent', true)
      }
    },
    saveCategory (item) {
      if (!item.categoryId) {
        this.$alert('请选择专区')
        return false
      }
      let flag = false
      item.productDisplayList.forEach(item => {
        if (item.isChange) {
          flag = true
        }
      })
      item.thirdCategoryList.forEach(item => {
        if (item.isChange) {
          flag = true
        }
      })
      if (flag) {
        this.$alert('请先确定修改项')
        return false
      }
      this.pageLoading = true
      getSavePage(item).then((res) => {
        if (res) {
          this.pageLoading = false
          if (Number(res.code) === 1) {
            this.$alert('保存成功')
            this.getCategoryPage()
          }
        }
      })
    },
    delCategory (item, index) {
      this.$confirm('确定删除该专区吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (item.isAdd) {
          this.formList.splice(index, 1)
        } else {
          getDelPages(item.categoryId).then((res) => {
            if (res) {
              if (Number(res.code) === 1) {
                this.getCategoryPage()
                this.$alert('删除成功')
              }
              this.pageLoading = false
            }
          })
        }
      }).catch(() => {})
    },
    updateSort (id, type) {
      this.pageLoading = true
      getUpdateSort({ categoryId: id, operation: type }).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            this.$alert('操作成功')
            this.getCategoryPage()
          }
          this.pageLoading = false
        }
      })
    },
    saveList (row, index) {
      if (!row.moduleStyle || row.moduleStyle === '') {
        this.$alert('请选择展示方式')
        return false
      }
      row.isChange = false
    },
    deleteListData (rows, index) {
      rows.splice(index, 1)
    },
    dataChange (val) {
      this.getBannerData(val)
    },
    addBanner () {
      const datas = {
        imagePath: '',
        redirectUrl: '',
        sort: '',
        isChange: true
      }
      this.bannerTableData.push(datas)
    },
    editBanner (row, index) {
      this.$set(row, 'isChange', true)
      this.$set(this.bannerTableData, index, row)
    },
    saveBanner (row, index) {
      if (!row.imagePath || row.imagePath === '') {
        this.$alert('请上传图片')
        return false
      }
      if (!row.sort || row.sort === '') {
        this.$alert('请输入展示顺序')
        return false
      }
      this.$set(row, 'isChange', false)
      this.$set(this.bannerTableData, index, row)
    },
    deleteBanner (rows, index) {
      rows.splice(index, 1)
    },
    moreSave (row, index) {
      if (!row.sort || row.sort === '') {
        this.$alert('请输入展示顺序')
        return false
      }
      this.$set(row, 'isChange', false)
    },
    moreEdit (row, index) {
      this.$set(row, 'isChange', true)
    },
    uploadProgress () {
      this.pageLoading = true
    },
    imageUpload (res, data) {
      this.pageLoading = false
      data.imagePath = res.obj.path
      this.$message.success('图片上传成功')
    },
    uploadError () {
      this.pageLoading = false
      this.$alert('上传失败，请稍后再试')
    },
    beforeUpload (file) {
      const ext = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
      const size = 2
      const fileName = file.name.split('.')
      const fileExt = fileName[fileName.length - 1]
      const isTypeOk = ext.indexOf(fileExt) >= 0
      const isSizeOk = file.size / 1024 / 1024 < size
      if (!isTypeOk) {
        this.$message.error(`上传图片只支持 ${ext.join(' / ')} 格式！`)
      }
      if (!isSizeOk) {
        this.$message.error(`上传图片大小不能超过 ${size}MB！`)
      }
      return isTypeOk && isSizeOk
    },
    refreshList (row) {
      this.pageLoading = true
      const params = {
        categoryId: row.categoryId
      }
      getRefreshData(params).then(res => {
        if (res) {
          if (Number(res.code) === 1) {
            const data = res.obj
            row.categoryId = data.categoryId
            row.thirdCategoryList = data.thirdCategoryList
          }
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
        this.$alert('刷新失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-head {
  display: flex;
  justify-content: flex-end;
}

.banner-setting {
  margin-top: 15px;
  background: #fff;
  padding: 15px;
  h1 {
    background: #fff;
    border-left: 4px solid #00aca1;
    line-height: 30px;
    font-size: 14px;
    padding-left: 10px;
  }

  .setting-form {
    margin-top: 20px;
  }
}
.setting-header{
  padding: 20px;
  background: #fff;
  display: flex;
  justify-content: space-between;
  border-bottom: 3px solid #f5f5f5;
}
.page-section{
    padding: 10px 15px;
    background: #fff;
    margin-bottom: 20px;
}
.list-setting {
  margin-top: 20px;
  h1 {
    background: #fff;
    border-left: 4px solid #00aca1;
    line-height: 30px;
    height: 30px;
    font-size: 14px;
    padding-left: 10px;
  }

  .setting-form {
    margin-top: 20px;
  }
}
.setting-more {
  margin-top: 10px;
  // h1 {
  //   background: #fff;
  //   border-left: 4px solid #00aca1;
  //   line-height: 30px;
  //   font-size: 14px;
  //   padding-left: 10px;
  // }
  .setting-radio {
    margin-top: 20px;
  }
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
